package com.library.servlet;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.library.dao.BookItem;
import com.library.dao.BookItemDAO;
import com.library.dao.BookTitle;
import com.library.dao.DAOFactory;
import com.library.dao.Lending;
import com.library.dao.LendingDAO;
import com.library.dao.MySQLDAOFactory;
import com.library.dao.Reservation;
import com.library.dao.ReservationDAO;
import com.library.dao.User;
import com.library.dao.UserDAO;

/**
 * Servlet implementation class LendingServlet
 */
@WebServlet("/LendingServlet")
public class LendingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LendingServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		int userid = Integer.parseInt(request.getParameter("userid"));
		int bookid = Integer.parseInt(request.getParameter("bookid"));
		int reservationid = 0;
		String rid = request.getParameter("reservationid");
		if (!rid.equals("")) {
			reservationid = Integer.parseInt(request
					.getParameter("reservationid"));
		}

		DAOFactory factory = new MySQLDAOFactory();
		UserDAO userDAO = factory.getUserDAO();
		User user = userDAO.findUser(userid);
		if (user != null) {
			ArrayList<BookTitle> borrowedBooks = userDAO.getBorrowedBook(
					userid, Resource.CONTINUOUS);

			if (borrowedBooks.size() < Resource.MAX_BOOK) {
				if (!userDAO.checkOverdateBook(userid)) {
					BookItemDAO bookItemDAO = factory.getBookItemDAO();
					BookItem book = bookItemDAO.findByKey(bookid);
					if (book != null) {
						Boolean allowed = true;
						for (BookTitle i : borrowedBooks) {
							if (i.getBookTitleId() == book.getBookTitleId()) {
								allowed = false;
								break;
							}
						}
						if (allowed) {
							if (reservationid != 0) {
								ReservationDAO rDAO = factory
										.getReverationDAO();
								Reservation resv = rDAO
										.findByKey(reservationid);
								if (resv != null
										&& resv.getStatus().equals(
												Resource.WAITTING)
										&& resv.getBookTitleId() == book
												.getBookTitleId()) {
									createLending(user, book, request, response);
									resv.setStatus(Resource.RECEIVED);
									rDAO.update(resv);
								} else {
									showError(Resource.ERROR_WRONG_RESERVED_ID,
											request, response);
								}
							} else {
								if (book.getStatus().equals(Resource.AVAILABLE)) {
									createLending(user, book, request, response);
								} else {
									showError("Sách đã được đặt trước", request,
											response);
								}
							}
						} else {
							showError(Resource.ERROR_BORROWED, request,
									response);
						}
					} else {
						showError(Resource.ERROR_WRONG_BOOK_ID, request,
								response);
					}
				} else {
					showError(Resource.ERROR_OVER_DUE, request, response);
				}
			} else {
				showError(Resource.ERROR_MAX_BOOK, request, response);
			}
		} else {
			showError(Resource.ERROR_WRONG_USER_ID, request, response);
		}

	}

	private void showError(String errorMsg, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("error", errorMsg);
		String add = "librarian/librarianerrorpage.jsp";
		request.setAttribute("lastpage", "librarian/lending.jsp");
		RequestDispatcher dispatcher = request.getRequestDispatcher(add);
		dispatcher.forward(request, response);
	}

	private void createLending(User user, BookItem book,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		DAOFactory factory = new MySQLDAOFactory();
		LendingDAO lendingDAO = factory.getLendingDAO();
		Lending lending = new Lending();
		lending.setBookItemId(book.getBookId());
		lending.setUserId(user.getUserId());
		lending.setDate(new Date(Calendar.getInstance().getTimeInMillis()));
		lendingDAO.insertLending(lending);
		
		BookItemDAO bookitemDAO = factory.getBookItemDAO();
		book.setStatus(Resource.BORROWED);
		bookitemDAO.update(book);

		request.setAttribute("msg", "Đã cho mượn");
		String add = "librarian/librariansuccesspage.jsp";
		request.setAttribute("lastpage", "librarian/lending.jsp");
		RequestDispatcher dispatcher = request.getRequestDispatcher(add);
		dispatcher.forward(request, response);
	}

}
